<template>
    <el-row type="flex" class="row-bg" justify="center">
        <!--上传头像-->
        <el-col :xl="6" :lg="7">
            <el-upload
                    class="avatar-uploader"
                    action="https://image.kieng.cn/upload.html?type=jd"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-col>
        <!--分割线-->
        <el-col :span="1" class="center-divider">
            <el-divider direction="vertical"></el-divider>
        </el-col>
        <!--表单-->
        <el-col :xl="6" :lg="7">
            <el-form status-icon :model="userInfo" :rules="rules" ref="userInfo" label-width="80px" class="demo-loginForm">
                <el-form-item label="用户名" prop="username">
                        <el-input v-model="userInfo.username"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                        <el-input @focus="passwordFormVisible = true" type="password" v-model="userInfo.password" readonly></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="modifyUsername('userInfo')">点击修改</el-button>
                </el-form-item>
            </el-form>
        </el-col>
        <el-dialog title="修改密码" :visible.sync="passwordFormVisible">
            <el-form :model="pass" :rules="rules" ref="pass" :label-width="formLabelWidth">
                <el-form-item label="旧密码" prop="oldPassword">
                    <el-input v-model="pass.oldPassword"  autocomplete="off" show-password></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="password">
                    <el-input v-model="pass.password"  autocomplete="off" show-password></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass">
                    <el-input v-model="pass.checkPass"  autocomplete="off" show-password></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="completeModify('pass')">取 消</el-button>
                <el-button type="primary" @click="modifyPassword('pass')">确 定</el-button>
            </div>
        </el-dialog>
    </el-row>
</template>

<script>
  export default {
    name: 'UserCenter',
      data() {
          // 用户名的规则
          const validateUserName = (rule, value, callback) => {
              if (!value) {
                  callback(new Error('请输入用户名'));
              }
              callback();
          };
          // 旧密码的规则
          const validateOldPassword = (rule, value, callback) => {
              if (!value) {
                  callback(new Error('请输入旧密码'));
              } else {
                  if (this.userInfo.password !== value) {
                      callback(new Error('旧密码输入错误'));
                  }
                  callback()
              }
          }
          // 新密码的规则
          const validatePass = (rule, value, callback) => {
              if (!value) {
                  callback(new Error('请输入新密码'));
              } else if (value === this.userInfo.password) {
                  callback(new Error('与旧密码相同'))
              } else {
                  if (this.pass.checkPass) {
                      this.$refs.pass.validateField('checkPass');
                  }
                  callback();
              }
          };
          // 确认密码的规则
          const validatePass2 = (rule, value, callback) => {
              if (!value) {
                  callback(new Error('请再次输入新密码'));
              } else if (value !== this.pass.password) {
                  callback(new Error('两次输入新密码不一致!'));
              } else {
                  callback();
              }
          };
          return {
              // 用户信息
              userInfo: {
                  username: '',
                  password: '',
                  avatar: '',
              },
              // 弹出框密码
              pass: {
                  oldPassword: '',
                  password: '',
                  checkPass: ''
              },
              // 验证规则
              rules: {
                  username: [
                      { validator: validateUserName, trigger: 'blur' },
                  ],
                  oldPassword: [
                      { validator: validateOldPassword, trigger: 'blur' }
                  ],
                  password: [
                      { validator: validatePass, trigger: 'blur' }
                  ],
                  checkPass: [
                      { validator: validatePass2, trigger: 'blur' }
                  ]
              },
              // 密码弹出框的显示隐藏
              passwordFormVisible: false,
              // 表单输入框文字宽度
              formLabelWidth: '80px'
          };
      },
      created() {
          this.getUserInfo()
      },
      methods: {
          // 获取个人信息
          getUserInfo() {
              this.$axios.get('/sys/userInfo').then(res => {
                  this.userInfo = res.data.data
              })
          },
          // 上传图片成功
          handleAvatarSuccess(res, file) {
              this.userInfo.avatar = URL.createObjectURL(file.raw);
          },
          // 上传图片前的格式验证
          beforeAvatarUpload(file) {
              const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
              const isLt2M = file.size / 1024 / 1024 < 2;

              if (!isJPG) {
                  this.$message.error('上传头像图片只能是 JPG/PNG/WEBP 格式!');
              }
              if (!isLt2M) {
                  this.$message.error('上传头像图片大小不能超过 2MB!');
              }
              return isJPG && isLt2M;
          },
          // 修改用户名
          modifyUsername(formName) {
              this.$refs[formName].validate((valid) => {
                  if (valid) {
                      this.$axios.post('/sys/modifyUserInfo',this.userInfo).then(res => {
                          this.userInfo = res.data.data
                          this.$message.success('修改信息成功！')
                      })
                  } else {
                      this.$message.error('修改信息失败！')
                      return false;
                  }
              });
          },
          // 修改个人密码
          modifyPassword(formName) {
              this.$refs[formName].validate((valid) => {
                  if (valid) {
                      this.userInfo.password = this.pass.checkPass
                      this.$axios.post('/sys/modifyUserInfo',this.userInfo).then(res => {
                          this.userInfo = res.data.data
                          this.completeModify(formName,true)
                      })
                  } else {
                      this.$message.error('修改信息失败！')
                      return false;
                  }
              });
          },
          // 弹出框完成修改信息
          completeModify(formName, complete = false) {
              this.$refs[formName].resetFields();
              this.pass = {
                  oldPassword: '',
                  password: '',
                  checkPass: ''
              };
              this.passwordFormVisible = false
              if (!complete) {
                  this.$message.info('取消修改！');
              } else {
                  this.$message.success('修改信息成功！')
              }

          }
      }
  }
</script>

<style lang="scss" scoped>
    /*用户信息行*/
    .el-row{
        width: 100%;
        display: flex;
        justify-content: center;
        padding-top: 150px;
        /*信息中的每一列*/
        .el-col{
            display: flex;
            justify-content: center;
            align-items: center;
            /*上传头像框*/
            .avatar-uploader {
                display: flex;
                justify-content: center;
                align-items: center;

                border: 1px solid #8c939d;
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
                /*头像图片*/
                .avatar {
                    width: 178px;
                    height: 178px;
                    display: block;
                }
                /*加号*/
                .avatar-uploader-icon {
                    font-size: 28px;
                    color: #8c939d;
                    width: 178px;
                    height: 178px;
                    line-height: 178px;
                    text-align: center;
                }
            }
            /*覆盖添加图片框时变色*/
            .avatar-uploader:hover {
                border-color: #409EFF;
                .avatar-uploader-icon {
                    color: #409EFF;
                }
            }

            /*分割线*/
            .el-divider{
                height: 150px;
            }

            /*用户信息表单*/
            .el-form{
                /*用户表单中的每一项*/
                .el-form-item{

                }
            }
        }
    }

    /*弹出框*/
    ::v-deep .el-dialog{
        width: 400px;
        margin-top: 25vh !important;
    }
    .el-dialog{
        /*弹出框表单*/
        .el-form{
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            .el-form-item{
                .el-input{
                    width: 90%;
                }
            }
        }
        /*弹出框底部*/
        .el-dialog__footer{
            padding: 0px 20px 20px;
        }
    }
</style>
